package com.rcp.login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rcp.objects.EmployeeBean;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

//	private static int x = 3;

	// The LoginServlet consists of a login form that has a username and password field
	// The LoginServlet DOES NOT do any authenticating but instead passes the username and password
	// to AuthenticateServlet to check if username and password matches with a username and password
	// from a list of users.
	// Every time someone goes to the servlet, it first checks for the parameter action.
	// Action basically notifies LoginServlet if a user had just clicked Log out from the WelcomeServlet page
	// or if any error messages need to be shown for incorrect login
	// If logout was clicked, it clears the users session and creates a new cookie with maxage set to 0 to
	// overwrite old cookie and kill the cookie.
	// After that it redirects user back to login page to make sure cookies are clear.

	private static final long serialVersionUID = 1L;
	
	String className = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
	String dbusername = "cs437group01";
	String dbpassword = "VHj#dj!v";
	
//	private String ClockOut;
//	private static final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
//	private static String dt;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		
		String pathToView = "/WEB-INF/login/Login.jsp";
		
		HttpSession session = request.getSession();
		// If Employee did not use login page, but has previously logged in and clicked remember me
		// Search for any cookies with Employee login
		if(session.getAttribute("loggedIn") == null){

			// Get reference to cookies
			Cookie[] cookies = request.getCookies();
			// Check if cookies has any data
			if( cookies != null ){
				// Look for data correct data
				for( int i = 0; i < cookies.length; i++ ){
					// get a reference to the current cookie
					Cookie cookie = cookies[i];
					// If the cookie is the 'Employee' cookie
					// then create a session variables for that Employee
					if(cookie.getName().equals("EmployeeID")){

						// Create the Session variables
						session.setAttribute("loggedIn", true);					
						session.setAttribute("EmployeeID", cookie.getValue());
						
						ResultSet resultSet = null;
						
						try{
							
							// Include the driver class
							Class.forName( className );
							
							// Establish a connection to the database
							Connection connection =
								DriverManager.getConnection(url, dbusername, dbpassword);			
							
							// Get a reference to the statement object that will execute our query
							// on the server
							Statement statement = connection.createStatement();
							
							resultSet = statement.executeQuery("SELECT * FROM Employees WHERE EmployeeID = " + cookie.getValue().trim());

							EmployeeBean employee = null;
							
							while(resultSet.next()){
								
								employee = new EmployeeBean(resultSet.getInt("EmployeeID"), resultSet.getString("FirstName"), resultSet.getString("LastName"), resultSet.getInt("status"));
								
							}
							
							session.setAttribute("employee", employee);
							
							resultSet = null;
							
							// Close our DB Connection
							connection.close();
													
						}
						catch(SQLException e){		
							e.printStackTrace();
						}
						catch(ClassNotFoundException e){
							e.printStackTrace();
						}
						
						
						break;

					}
				}
			}

		}
		
		if (session.getAttribute("loggedIn") != null) {
			
			pathToView = "/WEB-INF/login/Welcome.jsp";
			
			EmployeeBean user = (EmployeeBean) session.getAttribute("employee");
			
			switch(user.getStatus()){
			case 0:
				// WAITER
				request.setAttribute("path", "/rcp-svn/Ordering");
//				request.setAttribute("path", "/cs437group01/Ordering");
				break;
			case 1:
				// HOST
				request.setAttribute("path", "/rcp-svn/HostServlet");
//				request.setAttribute("path", "/cs437group01/HostServlet");
				break;
			case 2:
				// MANAGER
				request.setAttribute("path", "/rcp-svn/Nexus");
//				request.setAttribute("path", "/cs437group01/Nexus");
				break;
			}	
			
		}
		
		RequestDispatcher dispatcher =
				request.getRequestDispatcher( pathToView );
			
			dispatcher.forward(request, response);
		

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
